#include "gd32f4xx.h"
#include "gd32f4xx_gpio.h"
#include "stdbool.h"
#include "softspi.h"
#include "stdio.h"
extern void SoftSpiGpioInit(void);
extern void SckSetValue(bool value);
extern void MosiSetValue(bool value);
extern bool MisoGetValue(void);
extern void NssSetValue(bool value);

void MySPI_W_SS(bool BitValue)
{
		NssSetValue(BitValue);
}

void MySPI_W_SCK(bool BitValue)
{
		SckSetValue(BitValue);
}

void MySPI_W_MOSI(bool BitValue)
{
		MosiSetValue(BitValue);
}

bool MySPI_R_MISO(void)
{
		return MisoGetValue();
}


void MySPI_Init(void)
{
		SoftSpiGpioInit();
		MySPI_W_SS(1);
		MySPI_W_SCK(0);
}

void MySPI_Start(void){
		MySPI_W_SS(0);
}

void MySPI_Stop(void)
{
		MySPI_W_SS(1);
}
extern void xptdelay(uint32_t time);

uint8_t MySPI_SwapByte(uint8_t ByteSend){
	uint8_t i,ByteReceive = 0;
	
	for(i=0;i<8;i++)
	{
		MySPI_W_MOSI(ByteSend & (0x80 >> i));
		MySPI_W_SCK(1);
		if(MySPI_R_MISO() == 1)
		{
				ByteReceive |= (0x80 >> i);
		}//
		MySPI_W_SCK(0);
	}
	return ByteReceive;
}

uint32_t SwapData(uint8_t* data,uint8_t sizeInByte)
{ 
		uint8_t temp[4] = {0};
		uint32_t ret = 0;
		MySPI_Start();
		for(uint16_t i =0;i<sizeInByte;i++)
		{
				if(i == 0)
				{
						temp[i] = MySPI_SwapByte(data[i]);
				}else{
						temp[i] = MySPI_SwapByte(0);//dummytime
				}
				
		}
		
		for(uint8_t i = 0;i<sizeInByte;i++)
		{	
				ret = ret<<8;
				ret += temp[i];
		}
		MySPI_Stop();
		return ret;
}
